from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Conversation, Message
from .utils import get_chat_response


@login_required
def chat_view(request, conversation_id=None):
    # 新建对话
    if conversation_id is None:
        conversation = Conversation.objects.create(user=request.user)
        # 修改这里：使用正确的 URL 名称和命名空间
        return redirect('chat_app:chat_detail', conversation_id=conversation.id)

    conversation = get_object_or_404(Conversation, id=conversation_id, user=request.user)

    if request.method == 'POST':
        user_message = request.POST.get('message')

        # 保存用户消息
        Message.objects.create(
            conversation=conversation,
            role='user',
            content=user_message
        )

        # 获取AI回复

        ai_response = get_chat_response(conversation.id)

        # 保存AI消息
        Message.objects.create(
            conversation=conversation,
            role='assistant',
            content=ai_response
        )

        # 修改这里：使用正确的 URL 名称和命名空间
        return redirect('chat_app:chat_detail', conversation_id=conversation.id)

    messages = conversation.messages.all()
    return render(request, 'chat_app/chat.html', {
        'conversation': conversation,
        'messages': messages
    })


@login_required
def history_view(request):
    conversations = Conversation.objects.filter(user=request.user).order_by('-updated_at')
    return render(request, 'chat_app/history.html', {'conversations': conversations})


@login_required
def new_conversation(request):
    conversation = Conversation.objects.create(user=request.user)
    return redirect('chat_app:chat_detail', conversation_id=conversation.id)